import { NavBar, Toast } from "antd-mobile";
import QRCode from "qrcode.react";
import { useEffect, useRef } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import $fetch from "../../utils/app/$fetch";
import $reducer from "../../utils/app/$reducer";
import "./style.scss";

const View = () => {
  const navigate = useNavigate();
  const location: any = useLocation();
  const ticketRefs: any = useRef(null);
  const orderRefs: any = useRef(null);
  const initState: any = {
    isLoaded: false,
    quantity: 0,
  };

  const [state, dispatch] = $reducer({ ...initState });

  useEffect(() => {
    initPage();
    return () => {
      clearInterval(ticketRefs.current);
    };
  }, []);

  const initPage = () => {
    // 线下自提商品
    if (location?.state?.from === "order") {
      const { orderSn, goodsId } = location?.state;
      const value = `goodsId=${goodsId}&orderSn=${orderSn}`;
      dispatch({ isLoaded: true, value, title: "线下商品兑换码" });
      queryOrder(goodsId, orderSn);
    } else if (location?.state?.from === "tickets") {
      // 线上商品通用券
      const { goodsId, quantity, timingDuration, goodsName } = location?.state;
      const value = `goodsId=${goodsId}&timingDuration=${timingDuration}&goodsName=${goodsName}`;
      dispatch({ isLoaded: true, value, title: goodsName });
      queryTicket(goodsId, quantity);
    }
  };

  const queryTicket = (goodsId: any, quantity: any) => {
    ticketRefs.current = setInterval(async () => {
      try {
        const res: any = await $fetch(
          `ticketHolder/ticketHolderDetail/${goodsId}`,
          {},
          { loading: false }
        );
        if (res?.quantity !== quantity) {
          Toast.show("核销成功");
          clearInterval(ticketRefs.current);
          navigate("/home", { state: { current: "tickets" } });
        }
      } catch (error) {
        clearInterval(ticketRefs.current);
        console.log(error, "____error");
      }
    }, 500);
  };

  const queryOrder = async (goodsId: any, orderSn: any) => {
    orderRefs.current = setInterval(async () => {
      try {
        const res: any = await $fetch(
          `/order/queryGoodsRedeemed/${goodsId}?orderSn=${orderSn}`,
          {},
          { loading: false }
        );
        if (res === 1) {
          // 0为未兑换，1为已兑换
          Toast.show("核销成功");
          clearInterval(orderRefs.current);
          navigate("/order/list");
        }
      } catch (error) {
        clearInterval(orderRefs.current);
        console.log(error, "____error");
      }
    }, 500);
  };

  const back = () => {
    clearInterval(orderRefs.current);
    window.history.go(-1);
  };

  return (
    <div className="Container_Coupon">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={back}
      >
        {state?.title}
      </NavBar>
      {state?.isLoaded && (
        <div className="that_canvas_wraper">
          <QRCode value={state?.value} size={256} />
        </div>
      )}
    </div>
  );
};

export default View;